package cn.asterly.cicada.web.controller;

import cn.asterly.cicada.common.model.DataTablesResult;
import cn.asterly.cicada.common.model.Result;
import cn.asterly.cicada.common.utils.HttpUtil;
import cn.asterly.cicada.common.utils.IPInfoUtil;
import cn.asterly.cicada.model.Log;
import cn.asterly.cicada.model.LogWithBLOBs;
import cn.asterly.cicada.service.impl.LogServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @ Author     ：likun
 * @ Date       ：Created in 19:16 2019-02-28
 * @ Description：登录类
 * @Version: $
 */
@RestController
@RequestMapping(value = "login")
@Api(value = "login",description = "登录功能实现")
public class LoginController {
    @Autowired
    private LogServiceImpl logService;

    @RequestMapping(value = "/login")
    @ApiOperation(value = "用户名和密码登录",httpMethod = "POST")
    public Result Login(String username, String password, HttpServletRequest request){

        Log log=new LogWithBLOBs();
        String ipAddr = IPInfoUtil.getIpAddr(request);
        Subject subject =SecurityUtils.getSubject();
        String newPwd= DigestUtils.md5DigestAsHex(password.getBytes());

        UsernamePasswordToken token=new UsernamePasswordToken(username,newPwd);
        try {
            //执行登录
            subject.login(token);
            log.setId(UUID.randomUUID().toString());
            log.setLogtype("login");
            log.setUsername(username);
            log.setCreatetime(new Date());
            //写入登录的城市
            if(IPInfoUtil.isInnerIp(ipAddr)){
                log.setDescription("湖北省武汉市");
            }else{
                try {
                    log.setDescription(IPInfoUtil.getIpCity(ipAddr));
                } catch (Exception e) {
                    log.setDescription("湖北省武汉市");
                    e.printStackTrace();
                }
            }
            //写入登录地址
            log.setRequestip(ipAddr);
            ((LogWithBLOBs) log).setExceptiondetail("");
            if(!logService.insertSelective(log)){
                return new Result(false,"登录异常",5405,log);
            }

        } catch (AuthenticationException e) {
            e.printStackTrace();
            return new Result(false,"用户名或密码错误",5200,"");
        }
        return new Result(true,"登录成功",5200,"");
    }

    @RequestMapping(value = "loginerror")
    public Result loginError(){
        return new Result(false,"登录失败",5403);
    }

    @RequestMapping(value = "logiok")
    public Result loginSuccess(){
        return new Result(true,"登录成功",5200);
    }
    @RequestMapping(value = "unauthorized")
    public Result unauthorized(){
        return new Result(false,"权限不足",5403);
    }

    /**
     * @Description  获取ip地址
     * @Date 22:16 2019-03-01
     * @Param [request]
     * @return cn.asterly.cicada.common.model.DataTablesResult
     **/
    @RequestMapping(value = "/getIP")
    @ApiOperation(value = "用户名和密码登录",httpMethod = "GET")
    public DataTablesResult getIp(HttpServletRequest request){
        String ip=null;
        List list=new ArrayList();
        String ipAddr =IPInfoUtil.getIpAddr(request);
        list.add(ipAddr);
        return new DataTablesResult(true,ip,5200,list);
    }

    @RequestMapping(value = "/getBaiduIpinfo")
    @ApiOperation(value = "获取百度接口的ip信息",httpMethod = "GET")
    public String  getBaiDuInfo(HttpServletRequest request){
        String ip=IPInfoUtil.getIpAddr(request);
        String url=IPInfoUtil.getapiUrl(ip);
        return HttpUtil.sendGet(url);
    }

    @RequestMapping(value = "/getBaiduIpinfo/{ip}")
    @ApiOperation(value = "获取指定IP百度接口的ip信息",httpMethod = "GET")
    public String  getBaiDuInfo(HttpServletRequest request,@PathVariable String ip){
        String url=IPInfoUtil.getapiUrl(ip);
        return HttpUtil.sendGet(url);
    }



}
